import { defineStore } from 'pinia'
import { login, logout, getUserInfo } from '@/api/user'
import { getToken, setToken, removeToken, getUserInfo as getUserInfoFromStorage, setUserInfo, removeUserInfo, getPermissions, setPermissions } from '@/utils/auth'
import router from '@/router'
import MessageService from '@/utils/MessageService.js'

// 定义用户状态管理
export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户token
    token: getToken(),
    // 用户信息
    userInfo: getUserInfoFromStorage(),
    // 用户权限
    permissions: getPermissions(),
    // 登录状态
    isLoggedIn: !!getToken(),
    // 加载状态
    loading: false
  }),

  getters: {
    // 获取用户token
    getToken: (state) => state.token,
    // 获取用户信息
    getUserInfo: (state) => state.userInfo,
    // 获取用户权限
    getPermissions: (state) => state.permissions,
    // 获取登录状态
    getIsLoggedIn: (state) => state.isLoggedIn,
    // 获取加载状态
    getLoading: (state) => state.loading,
    // 获取用户角色
    getUserRoles: (state) => {
      return state.userInfo?.roles || []
    },
    // 获取用户姓名
    getUserName: (state) => {
      return state.userInfo?.username || ''
    },
    // 获取用户昵称
    getUserNickname: (state) => {
      return state.userInfo?.nickname || ''
    },
    // 获取用户头像
    getUserAvatar: (state) => {
      return state.userInfo?.avatar || ''
    }
  },

  actions: {
    // 登录
    async login(loginForm) {
      try {
        this.loading = true
        const { username, password, rememberMe } = loginForm
        const response = await login({ username, password })
        const { token } = response.data
        
        // 设置token
        setToken(token, rememberMe)
        this.token = token
        this.isLoggedIn = true
        
        // 获取用户信息
        await this.getUserInfoAction()
        
        MessageService.success('登录成功')
        return Promise.resolve(response)
      } catch (error) {
        MessageService.error(error.message || '登录失败')
        return Promise.reject(error)
      } finally {
        this.loading = false
      }
    },

    // 获取用户信息
    async getUserInfoAction() {
      try {
        if (!this.token) {
          return Promise.reject(new Error('token不存在'))
        }
        
        const response = await getUserInfo()
        // 确保response和response.data存在且为对象
        const userInfo = (response && typeof response === 'object' && response.data) || {}
        
        // 确保userInfo是一个对象
        const safeUserInfo = (userInfo && typeof userInfo === 'object') ? userInfo : {}
        
        // 统一角色格式为roles数组，以兼容前端各处使用
        if (safeUserInfo.role && !safeUserInfo.roles) {
          safeUserInfo.roles = [safeUserInfo.role]
        }
        
        // 确保roles属性始终存在且为数组
        if (!safeUserInfo.roles || !Array.isArray(safeUserInfo.roles)) {
          safeUserInfo.roles = []
        }
        
        // 设置用户信息
        setUserInfo(safeUserInfo)
        this.userInfo = safeUserInfo
        
        // 设置权限信息，确保permissions是一个数组
        const permissions = safeUserInfo.permissions && Array.isArray(safeUserInfo.permissions) ? safeUserInfo.permissions : []
        setPermissions(permissions)
        this.permissions = permissions
        
        return Promise.resolve(response)
      } catch (error) {
        console.error('获取用户信息失败:', error)
        // 设置默认用户信息，防止出现undefined访问错误
        const defaultUserInfo = {
          roles: ['TESTER']
        }
        setUserInfo(defaultUserInfo)
        this.userInfo = defaultUserInfo
        this.permissions = []
        
        // token无效时，清除token
        if (error.response && error.response.status === 401) {
          this.logout()
        }
        
        MessageService.error('获取用户信息失败')
        return Promise.resolve() // 返回resolve而不是reject，确保应用能够继续运行
      }
    },

    // 登出
    async logout() {
      try {
        // 调用登出接口
        await logout()
      } catch (error) {
        console.error('登出失败:', error)
      } finally {
        // 清除token
        removeToken()
        this.token = ''
        
        // 清除用户信息，但保留一个基础对象以防止undefined访问错误
        removeUserInfo()
        this.userInfo = { roles: [] }
        
        // 清除权限
        localStorage.removeItem('permissions')
        this.permissions = []
        
        // 设置登录状态
        this.isLoggedIn = false
        
        // 跳转到登录页面
        router.replace('/login')
        
        // 提示登出成功
        MessageService.success('登出成功')
      }
    },

    // 清除token
    resetToken() {
      removeToken()
      this.token = ''
      this.isLoggedIn = false
    },

    // 设置用户信息
    setUserInfoAction(userInfo) {
      setUserInfo(userInfo)
      this.userInfo = userInfo
    },

    // 设置权限
    setPermissionsAction(permissions) {
      setPermissions(permissions)
      this.permissions = permissions
    },

    // 检查权限
    hasPermission(permission) {
      if (!permission) {
        return true
      }
      return this.permissions.includes(permission)
    },

    // 检查角色
    hasRole(role) {
      if (!role) {
        return false
      }
      // 确保userInfo存在且为对象，并且roles是数组
      if (!this.userInfo || typeof this.userInfo !== 'object') {
        return false
      }
      const roles = Array.isArray(this.userInfo.roles) ? this.userInfo.roles : []
      return roles.includes(role)
    }
  }
})

export default useUserStore